package com.rp.system.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rp.system.user.entity.SysRolePermission;
import com.rp.system.user.mapper.SysRolePermissionMapper;
import com.rp.system.user.model.SysRolePermissionModel;
import com.rp.system.user.service.SysRolePermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色权限表 服务实现类
 * </p>
 *
 * @author vicente
 * @since 2020-12-01
 */
@Service
public class SysRolePermissionServiceImpl extends ServiceImpl<SysRolePermissionMapper, SysRolePermission> implements SysRolePermissionService {

    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    @Override
    public Boolean insertOrDelete(SysRolePermissionModel sysRolePermissionModel){

        Boolean boo = true;

        List<SysRolePermission> list = super.list(new QueryWrapper<SysRolePermission>().select("permission_id").eq("role_id",sysRolePermissionModel.getRoleId()));
        List<String> permissionIds = list.stream().map(SysRolePermission::getPermissionId).collect(Collectors.toList());
        List<String> permissionIds2 = new ArrayList<>(sysRolePermissionModel.getPermissionIds());

        //需要增加的
        sysRolePermissionModel.getPermissionIds().removeAll(permissionIds);
        for(String string : sysRolePermissionModel.getPermissionIds()){
            boo = super.save(new SysRolePermission(sysRolePermissionModel.getRoleId(),string));
            if(!boo){
                return false;
            }
        }

        //需要删除的
        permissionIds.removeAll(permissionIds2);
        for(String string : permissionIds){
            boo = super.remove(new QueryWrapper<SysRolePermission>().eq("role_id", sysRolePermissionModel.getRoleId()).eq("permission_id", string));
            if(!boo){
                return false;
            }
        }
        return boo;
    }

    public static void main(String[] args){
        //开始main方法
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        List<Integer> list2 = new ArrayList<>();
//        list2.add(4);
//        list2.add(4);
//        list2.add(4);

    }
}
